<template>
	<view>
		<uni-nav-bar fixed statusBar="" title="账户" :border="false" backgroundColor="#ffcd54" color="#fff"></uni-nav-bar>
		<view class="generalize">
			<image class="money_drawing" src="/static/images/home/money-drawing.png" mode="heightFix"></image>
			<view class="generalize_box">
				<view class="fs26 mb10 text-white">总金额(元)</view>
				<view class="fs40 fw700 text-white">￥{{ accountDetail.totalMoney }}</view>
			</view>
			<view class="generalize_tally dis_center_s">
				<view class="dis_center">
					<text class="fs26 text-white">待还</text>
					<text class="fs36 text-white ml10">￥{{ accountDetail.paidMoney }}</text>
				</view>
				<view class="dis_center">
					<text class="fs26 text-white">结余</text>
					<text class="fs36 text-white ml10">￥{{ accountDetail.surplusMoney }}</text>
				</view>
			</view>
			<button class="basic_button generalize_btn" @click="add">新增</button>
		</view>
		<view class="p20">
			<view class="mb20" v-for="item in current" :key="item.value">
				<view class="pb20 fw700">{{ item.text }}</view>
				<view class="pl15">
					<template v-if="['2', '3', '4'].includes(item.value)">
						<view v-for="val in item.children" :key="val._id">
							<view class="dis_center_s pr15">
								<view>
									<text>{{ val.accountName }}</text>
									<text>丨</text>
									<text>{{ formatNumber(val.accountNumber) }}</text>
								</view>
								<uni-icons type="more-filled" :size="16" @click="actionAccount(val)"></uni-icons>
							</view>
							<template v-if="val.accountType === '3'">
								<view class="dis_center_s">
									<view class="dis">
										<view class="dis_column pt10 pb10">
											<text class="fs36 fw700 pt10 pb10 mr20">￥{{ val.balance }}</text>
											<text class="fs28 text-info">当前余额</text>
										</view>
										<view class="dis_column pt10 pb10 text-danger">
											<text class="fs36 fw700 pt10 pb10">￥-{{ val.paidPrice }}</text>
											<text class="fs28 text-info">当前应还</text>
										</view>
									</view>
									<view class="surplus">
										<view class="pt10 pb10">
											<text class="fs28 text-info">剩余</text>
											<text class="pl10 pr10 fs38 fw700">{{ val.surplus }}</text>
											<text class="fs28 text-info">天</text>
										</view>
										<text class="fs28 text-info">还款日{{ val.paidLabel }}</text>
									</view>
								</view>
							</template>
							<template v-else>
								<view class="dis">
									<view class="dis_column pt10 pb10">
										<text class="fs36 fw700 pt10 pb10">￥{{ val.balance }}</text>
										<text class="fs28 text-info">当前余额</text>
									</view>
								</view>
							</template>
						</view>
					</template>
					<template v-else>
						<view class="other" v-for="val in item.children" :key="val._id">
							<view class="dis_column pt10 pb10">
								<text class="fs36 fw700 pt10 pb10">￥{{ val.balance }}</text>
								<text class="fs28 text-info">当前余额</text>
							</view>
							<view class="pr15">
								<uni-icons type="more-filled" :size="16" @click="actionAccount(val)"></uni-icons>
							</view>
						</view>
					</template>
				</view>
			</view>
		</view>
		<uni-popup type="bottom" ref="accountRefs" @change="popupChange">
			<view class="account_popup">
				<uni-forms ref="form" :model="formData" label-position="left" label-width="80px" :rules="rules">
					<uni-forms-item required label="账户性质" name="accountType">
						<uni-data-checkbox v-model="formData.accountType" :localdata="payList" />
					</uni-forms-item>
					<uni-forms-item required label="账户名称" name="accountName">
						<uni-easyinput trim="both" v-model="formData.accountName" placeholder="请输入账户名称"
							@iconClick="iconClick" suffixIcon="camera" />
					</uni-forms-item>
					<uni-forms-item v-if="['2', '3', '4'].includes(formData.accountType)" required label="账户帐号" name="accountNumber">
						<uni-easyinput trim="both" type="number" v-model="formData.accountNumber"
							placeholder="请输入账户帐号" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.accountType === '3'" required label="额度上限" name="quotaUp">
						<uni-easyinput trim="both" v-model="formData.quotaUp"
							placeholder="请输入额度上限" />
					</uni-forms-item>
					<uni-forms-item required label="余额" name="balance">
						<uni-easyinput trim="both" v-model="formData.balance"
							placeholder="请输入余额" @change="balanceChange" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.accountType === '3'" required label="待还金额" name="paidPrice">
						<uni-easyinput trim="both" v-model="formData.paidPrice"
							placeholder="请输入待还金额" />
					</uni-forms-item>
					<uni-forms-item v-if="formData.accountType === '3'" required label="还款日期">
						<uniPaid :paids="totalDays" :value="formData.paidTime" @selected="selected" />
					</uni-forms-item>
					<button class="basic_button uni_forms_button mt40" @click="submit">提交</button>
				</uni-forms>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniPaid from '../../components/uni-paid/index.vue'
	import store from '../../store/index.js'
	import { pathToBase64 } from 'image-tools'
	import {
		payList
	} from '../../utils/dict-data.js'
	import { getBaiduAuth, getAccurateBank } from '../../config/index.js'
	import moment from 'moment'
	const uniclound = uniCloud.importObject('account')
	export default {
		components: {
			uniPaid
		},
		data() {
			return {
				payIndex: undefined,
				payList,
				formData: {},
				rules: {
					accountName: {
						rules: [{ required: true, errorMessage: '请填写账户名称'}]
					},
					accountNumber: {
						rules: [{required: true, errorMessage: '请填写账户帐号' }, { pattern: '^[\\d\\s]+$' , errorMessage: '账户帐号格式输入错误'  }]
					},
					accountType: {
						rules: [{required: true,errorMessage: '请选择账户性质'}]
					},
					quotaUp: {
						rules: [{ required: true, errorMessage: '请填入额度上限' }, { pattern: '^(-?\\d*(\\.\\d+)?)$', errorMessage: '额度上限格式输入错误' }]
					},
					balance: {
						rules: [{ required: true, errorMessage: '请填入余额' }, { pattern: '^(-?\\d*(\\.\\d+)?)$', errorMessage: '余额格式输入错误' }]
					},
					paidPrice: {
						rules: [{ required: true, errorMessage: '请填入待还金额' }, { pattern: '^(-?\\d*(\\.\\d+)?)$', errorMessage: '待还金额格式输入错误' }]
					}
				},
				tableData: [],
				totalDays: 27,
				isEdit: false
			}
		},
		onShow() {
			this.initAccount()
		},
		computed: {
			current() {
				return this.tableData.reduce((arr, row) => {
					const index = arr.findIndex(c => c.value === row.accountType)
					const find = this.payList.find(c => c.value === row.accountType)
					if(row.paidTime) {
						row.surplus = this.daysToTarget(row.paidTime)
						row.paidLabel = ` ${moment().month() + 1}月${row.paidTime}日`
					}
					index === -1 && arr.push({ text: find.text, value: find.value, children: [row] })
					index !== -1 && arr[index].children.push(row)
					return arr
				}, [])
			},
			accountDetail() {
				const data = this.tableData.reduce((obj, row) => {
					row.accountType !== '3' && (obj.totalMoney += Number(row.balance))
					row.accountType === '3' && (obj.paidMoney += Number(row.paidPrice))
					return obj
				}, { totalMoney: 0, paidMoney: 0 })
				data.surplusMoney = data.totalMoney - data.paidMoney
				for (let key in data) {
					data[key] = data[key].toFixed(2)
				}
				return data
			}
		},
		methods: {
			initAccount() {
				uniclound.getAccout().then(res => {
					this.tableData = res.data
				})
			},
			iconClick(key) {
				const that = this
				if(key === 'suffix') {
					uni.chooseImage({
						count: 1,
						success(res) {
							uni.showLoading({
								title: '加载中...'
							})
							const image = res.tempFilePaths[0]
							let token = ''
							getBaiduAuth().then(ret => {
								token = ret.token
								return pathToBase64(image)
							}).then(base64 => {
								const url = decodeURIComponent(base64)
								const [, base] = url.split('base64,')
								return getAccurateBank({ image: base, token })
							}).then(ret => {
								that.formData.accountName = ret.bankName
								that.formData.accountNumber = ret.bankCardNumber
								that.$forceUpdate()
								uni.hideLoading()
							}).catch(() => uni.hideLoading())
						}
					})
				}
			},
			add() {
				this.formData = {}
				this.$refs.accountRefs.open()
			},
			selected(index) {
				this.formData.paidTime = index
			},
			submit() {
				this.$refs.form.validate().then(res => {
					if(this.isEdit) {
						return uniclound.updateAccount(this.formData)
					} else {
						const data = { ...this.formData, userId: store.state.user.userInfo.uid }
						return uniclound.addAccount(data)
					}
				}).then(res => {
					this.$refs.accountRefs.close()
					uni.showToast({
						title: '操作成功'
					})
					this.initAccount()
				})
			},
			formatNumber(value) {
				const start = value.slice(0, 4)
				const end = value.slice(value.length - 5, value.length - 1)
				return `${start}****${end}`
			},
			daysToTarget(targetDay) {
			  const now = moment().set({ month: moment().month(), date: moment().date() });
			  
			  // 获取本月目标日期
			  const thisMonthTargetDate = moment(now).set({ date: targetDay });
			
			  // 如果目标天数大于当前天数，则计算两者之间的天数
			  if (thisMonthTargetDate.isAfter(now)) {
			    return thisMonthTargetDate.diff(now, 'days')
			  } else { // 否则，计算到下月目标天数的天数
			    const nextMonthTargetDate = moment(now).add(1, 'months').set({ date: targetDay });
			    return nextMonthTargetDate.diff(now, 'days')
			  }
			},
			popupChange(e) {
				if(!e.show) {
					this.formData = {}
					this.isEdit = false
				}
			},
			actionAccount(scope) {
				const that = this
				uni.showActionSheet({
					itemList: ['修改', '删除'],
					success(res) {
						if(res.tapIndex === 0) {
							that.formData = Object.assign({}, scope)
							console.log(that.formData);
							that.isEdit = true
							that.$refs.accountRefs.open()
						} else {
							uni.showModal({
								title: '提醒',
								content: '确认删除吗?',
								success(ret) {
									if(ret.confirm) {
										uniclound.deleteAccount(scope._id).then(() => {
											uni.showToast({
												title: '操作成功'
											})
											that.initAccount()
										})
									}
								}
							})
						}
					}
				})
			},
			balanceChange() {
				if(this.formData.accountType === '3' && this.formData.balance && this.formData.quotaUp) {
					this.formData.paidPrice = (Number(this.formData.quotaUp) - Number(this.formData.balance)).toFixed(2)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.generalize {
		position: relative;
		height: 320rpx;
		background-color: #ffcd54;

		.money_drawing {
			position: absolute;
			top: 0;
			right: 0;
			width: 100%;
			height: 100%;
		}

		.generalize_box {
			position: absolute;
			top: 60rpx;
			left: 30rpx;
			z-index: 1;
		}

		.generalize_tally {
			position: absolute;
			top: 180rpx;
			left: 30rpx;
			width: 600rpx;
			z-index: 1;
		}

		.generalize_menus {
			position: absolute;
			left: 50%;
			bottom: -110rpx;
			transform: translateX(-50%);
			width: 700rpx;
			border-radius: 12rpx;
			background-color: #fff;
			z-index: 1;
			box-shadow: 0 0 20rpx 1rpx #ccc;
			box-sizing: border-box;
		}
		.generalize_btn {
			position: absolute;
			bottom: 17rpx;
			left: 30rpx;
			height: 60rpx;
			width: 150rpx;
			background-color: #ffcd54;
			color: #fff;
			border: 1rpx solid #fff;
			box-shadow: node;
		}
	}

	.account_popup {
		padding: 40rpx 30rpx;
		background-color: #fff;
		.uni_forms_button {
			background-color: red;
			color: #fff;
		}
	}
	.surplus {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
	}
	.other {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
	}
</style>